import {formatToDateTime} from "/@/utils/dateUtil";
import {isDevMode} from "/@/utils/env";
import {decodeByBase64, encryptByBase64, encryptByMd5} from "/@/utils/cipher";

/**
 * 定制工具类
 */
export class CoreUtils {

  /**
   * 有效账号检测（2-30位）
   */
  static isAccount(txt: string) {
    return txt.match(/^[\u4E00-\u9FA5A-Za-z0-9]{2,30}$/) == null ? false : true;
  }

  /**
   * 有效密码检测（6-15位）
   */
  static isPassword(txt: string) {
    return txt.match(/^[a-zA-Z0-9]{6,15}$/) == null ? false : true;
  }

  /**
   * 有效手机号检测
   */
  static isPhoneNumber(txt: string) {
    return txt.match(/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/) == null ? false : true;
  }

  /**
   * 有效邮箱检测
   */
  static isEmail(txt: string) {
    return txt.match(/^(.+)@(.+)$/) == null ? false : true;
  }

  /**
   * 将"秒"转为"X天X小时X分X秒"
   */
  static getDuration(second) {
    var days = Math.floor(second / 86400);
    var hours = Math.floor((second % 86400) / 3600);
    var minutes = Math.floor(((second % 86400) % 3600) / 60);
    var seconds = Math.floor(((second % 86400) % 3600) % 60);
    var duration = days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
    return duration;
  }

  /**
   * 存储持久数据
   */
  static setLocalStorage(key: string, value: string) {
    if (window.localStorage) {
      const encKey = encryptByMd5(key);
      const base64Value = encryptByBase64(value);
      window.localStorage.setItem(encKey, base64Value);
    }
  }

  /**
   * 获取持久数据
   */
  static getLocalStorage(key: string) {
    if (window.localStorage) {
      const encKey = encryptByMd5(key);
      const base64Value = window.localStorage.getItem(encKey);
      if (null != base64Value) {
        const value = decodeByBase64(base64Value);
        return value;
      }
    }
    return null;
  }

  /**
   * 删除持久数据
   */
  static removeLocalStorage(key: string) {
    if (window.localStorage) {
      const encKey = encryptByMd5(key);
      window.localStorage.removeItem(encKey);
    }
  }

  /**
   * 开发者模式打印日志
   */
  static console_log(log) {
    if (isDevMode()) {
      console.log(log);
    }
  }

  /**
   * 开发者模式打印TAG日志
   */
  static console_tag_log(tag, log) {
    if (isDevMode()) {
      const dateTime = formatToDateTime();
      console.log(dateTime + ' : ' + tag + ' => ');
      console.log(log);
    }
  }

}
